namespace EyeOpen.SampleCms.Web.Contents
{
    using System.IO;
    using System.Web;
    using EyeOpen.SampleCms.Web.Data.Serialization;

    public class XmlSectionContentProvider : SectionContentProvider
    {
        public override SectionContent CurrentSectionContent
        {
            get
            {
                if (HttpContext.Current.Items["CurrentSectionContent"] == null)
                {
                    if (File.Exists(CurrentContentPath))
                    {
                        var contentSerializer = new XmlSerializer<SectionContent>(CurrentContentPath);
                        HttpContext.Current.Items["CurrentSectionContent"] = contentSerializer.Deserialize();
                    }
                    else
                    {
                        HttpContext.Current.Items["CurrentSectionContent"] = new SectionContent();
                    }
                }

                return (SectionContent)HttpContext.Current.Items["CurrentSectionContent"];
            }
        }

        private static string CurrentContentPath
        {
            get
            {
                var xmlPath = VirtualPathUtility.ToAppRelative(HttpContext.Current.Request.Path);
                var extension = VirtualPathUtility.GetExtension(xmlPath);
                xmlPath = xmlPath.TrimStart("~/".ToCharArray());
                xmlPath = xmlPath.Replace(extension, string.Empty);
                xmlPath = xmlPath.Replace("/", "_");
                xmlPath = xmlPath.TrimEnd("_".ToCharArray());
                xmlPath += ".xml";
                xmlPath = Path.Combine(HttpContext.Current.Server.MapPath(ConfigurationWrapper.ContentsPath), xmlPath);
                return xmlPath;
            }
        }

        public override void Save()
        {
            if (CurrentSectionContent == null)
            {
                return;
            }

            var contentSerializer = new XmlSerializer<SectionContent>(CurrentContentPath);
            contentSerializer.Serialize(CurrentSectionContent);
        }
    }
}